<?php
namespace App\Http\Controllers\Pc;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class UserController extends Controller{
//////////////////////////////////////////////// 用户
////////////////////// 用户列表
///
    public function __construct(Request $request)
    {
        $this->request = $request;
    }
	/**
	 * 用户列表--数据
	 * @param account 账号
	 * @param email 邮箱
	 * @param state 状态：1正常 2禁用
	 * @apram create_time 创建时间
	 * @param page 页码
	 * @param page_count 每页条数
	 */
	public function user_list(Request $request){
		$data = $request->all();
		if(empty($data)){
			$this->back('接收值为空');
		}
		
		$call_user = new \App\Libs\wrapper\User();
		$return = $call_user->user_list($data);
//		var_dump($return);exit;
		if(is_array($return['list'])){
			$this->back('获取成功', '200', $return);
		}else{
			$this->back($return);
		}
	}
	
	/**
	 * 新增用户
	 * @parma account 账号
	 * @param password 密码
	 * @paran phone 联系电话
	 * @param sex 性别：1.男、2.女
	 * @param email 邮箱
	 */
	public function user_add(Request $request){
		$this->validate($request, [
			'account' => 'required| string',
			'password' => 'required| string',
		], [
			'account.required' => '请填写账号',
			'account.string' => 'account必须是字符串',
			'password.required' => '请填写登录密码',
			'password.string' => 'password必须是字符串',
		]);
		
		$data = $request->all();
		////权限验证
		$arr = array();
		$arr['user_id'] = $data['user_info']['Id'];
		$arr['identity'] = array('user_add');
		$powers = $this->powers($arr);
		if(!$powers['user_add']){
			$this->back('无该权限');
		}
		$call_user = new \App\Libs\wrapper\User();
		$return = $call_user->user_add($data);
//		var_dump($return);exit;
		if($return === 1) {
			$this->back('新增成功', '200');
		}else if($return === 2){
			$this->back('已将该用户恢复正常', '200');
		}else{
			$this->back($return);
		}
	}

    /**
     * 部门新增成员
     * @parma user_id 用户id
     * @param organize_id 部门id
     */

    public function organize_add(Request $request){
        $data = $request->all();
        ////权限验证
        $arr = array();
        $arr['user_id'] = $data['user_info']['Id'];
        $arr['identity'] = array('user_add');
        $powers = $this->powers($arr);
        if(!$powers['user_add']){
            $this->back('无该权限');
        }
        $call_user = new \App\Libs\wrapper\User();
        $return = $call_user->organize_add($data);
        if($return === 1) {
            $this->back('新增成功', '200');
        }{
            $this->back($return);
        }
    }
	/**
	 * 用户信息
	 * @param user_id 用户id
	 */
	public function user_info(Request $request){
		$this->validate($request, [
			'user_id' => 'required| integer',
		], [
			'user_id.required' => 'user_id为空',
			'user_id.integer' => 'user_id必须是整型数字',
		]);
		
		$sql = "select *
					from users
					where `Id` = {$request->user_id}";
		$find = json_decode(json_encode(db::select($sql)),true);
		if(empty($find)){
			$this->back('无该用户');
		}else{
			$this->back('获取成功', '200', $find[0]);
		}
	}
	
	/**
	 * 编辑用户
	 * @param Id 用户id
	 * @param account 账号
	 * @param password 密码
	 * @param heard_img 头像
	 * @param email 邮箱
	 * @paran phone 联系电话
	 * @param sex 性别：1.男、2.女
	 * @param state 状态：1正常 2禁用
	 * @param update_type 修改类型：user_list 用户列表页面、user_info 个人中心页面
	 */
	public function user_update(Request $request){
		$this->validate($request, [
			'Id' => 'required| integer',
		], [
			'Id.required' => 'Id为空',
			'Id.integer' => 'Id必须是整型数字',
		]);
		
		$data = $request->all();
		////权限验证
		if($data['update_type'] == 'user_list'){
			$arr = array();
			$arr['user_id'] = $data['user_info']['Id'];
			$arr['identity'] = array('user_update');
			$powers = $this->powers($arr);
			if(!$powers['user_update']){
				$this->back('无该权限');
			}
		}
		
		$call_user = new \App\Libs\wrapper\User();
		$return = $call_user->user_update($data);
//		var_dump($return);exit;
		if($return === 1) {
			$this->back('操作成功', '200');
		}else{
			$this->back($return);
		}
	}
	
	/**
	 * 删除用户
	 * @param Id 用户id
	 * @param state 状态：1正常 2禁用
	 */
	public function user_del(Request $request){
		$this->validate($request, [
			'Id' => 'required| integer',
		], [
			'Id.required' => 'Id为空',
			'Id.integer' => 'Id必须是整型数字',
		]);
		
		$data = $request->all();
		////权限验证
		$arr = array();
		$arr['user_id'] = $data['user_info']['Id'];
		$arr['identity'] = array('user_del');
		$powers = $this->powers($arr);
		if(!$powers['user_del']){
			$this->back('无该权限');
		}
		$call_user = new \App\Libs\wrapper\User();
		$return = $call_user->user_update($data);
		if($return === 1) {
			$this->back('删除成功', '200');
		}else{
			$this->back($return);
		}
	}
	
	/**
	 * 获取角色
	 */
	public function role_list(Request $request){
        $data = $request->all();
        //验证是否有所有部门权限
        $identity = 'department_all';
        //var_dump($data);die;
        $userId = $data['user_info']['Id'];
        $sqlPower = "select pr.*,xr.*
				       from xt_role_user_join xruj
				       left join (select xprj.role_id, xprj.power_id, xp.*
				                         from xt_powers_role_join xprj
				                         inner join xt_powers xp on xp.Id=xprj.power_id
                                      ) as pr on pr.role_id = xruj.role_id
                       left join xt_role xr on xr.Id = pr.role_id 
				       where xruj.user_id={$userId} and pr.identity = '{$identity}'
				       group by pr.power_id";

        $power_list = json_decode(json_encode(db::select($sqlPower)), true);
        if (empty($power_list)) {
            $sql = "select r.pid
					from xt_role r
					left join xt_role_user_join ruj on r.Id=ruj.role_id
					where ruj.user_id={$userId}";
            $role = json_decode(json_encode(db::select($sql)),true);
            //var_dump($role);die;
            $pid = $role[0]['pid'];
            $sql = "select *
					from xt_role 
					where pid={$pid}";
            $role_data = json_decode(json_encode(db::select($sql)),true);
            $sql = "select *
					from xt_role 
					where Id={$pid}";
            $role = json_decode(json_encode(db::select($sql)),true);
            $role[0]['child'] = $role_data;
            $list = $role;
            //var_dump($role);die;

        }else{
            $sql = "select *
					from xt_role where pid=0";
            $role = json_decode(json_encode(db::select($sql)),true);
            $sql = "select *
					from xt_role where pid!=0";
            $role_data = json_decode(json_encode(db::select($sql)),true);
            foreach ($role as $key=>$value) {
                foreach ($role_data as $k=>$v){
                    if($v['pid']===$value['Id']){
                        //var_dump($value);die;
                        //$id = $value['Id'];
                        //var_dump($id);die;
                        $value['child'][] = $v;
                        //var_dump($value);die;
                    }
                }
                $list[] = $value;

            }
            //var_dump($list);die;

        }


		if(is_array($list)){
			$this->back('获取成功', '200', $list);
		}else{
			$this->back('获取失败');
		}
	}
	
	/**
	 * 获取用户角色
	 * @param user_id 用户id
	 */
	public function user_role_get(Request $request){
		$this->validate($request, [
			'user_id' => 'required| integer',
		], [
			'user_id.required' => 'user_id为空',
			'user_id.integer' => 'user_id必须是整型数字',
		]);
		
		$sql = "select r.Id, r.name
					from xt_role_user_join ruj
					left join xt_role r on r.Id = ruj.role_id
					where ruj.user_id = {$request->user_id}";
		$roles = json_decode(json_encode(db::select($sql)),true);
		if(is_array($roles)){
			$this->back('获取成功', '200', $roles);
		}else{
			$this->back('获取失败');
		}
	}
	
	/**
	 * 修改用户角色
	 * @param user_id 用户id
	 * @param id_del 删除角色id  例如：1,2,3
	 * @param id_add 新增角色id  例如：1,2,3
	 */
	public function user_role_update(Request $request){
		$this->validate($request, [
			'user_id' => 'required| integer',
		], [
			'user_id.required' => 'user_id为空',
			'user_id.integer' => 'user_id必须是整型数字',
		]);
		
		$data = $request->all();
		////权限验证
		$arr = array();
		$arr['user_id'] = $data['user_info']['Id'];
		$arr['identity'] = array('user_update');
		$powers = $this->powers($arr);
		if(!$powers['user_update']){
			$this->back('无该权限');
		}
		$call_user = new \App\Libs\wrapper\User();
		$return = $call_user->user_role_update($data);
		if($return === 1){
			$this->back('操作成功', '200');
		}else{
			$this->back($return);
		}
	}

////////////////////// 个人中心
	/**
	 * 消息列表--数据
	 */
	public function tiding_list(Request $request){

		$data = $request->all();

        $tidingMdl = DB::table('tidings')
            ->where('user_js', $data['user_info']['Id']);
//        $where = "user_js={$data['user_info']['Id']}";
		if(!empty($data['key'])){
//            $where.= " and title like '%{$data['key']}%' ";
            $tidingMdl = $tidingMdl->where('title', 'like', '%'.$data['key'].'%');
        }
//		$sql = "select *
//					from tidings
//					where $where
//					order by `Id` desc";
//		$list = json_decode(json_encode(db::select($sql)),true);
        $limit = $data['limit'] ?? 100;
        $page = $data['page'] ?? 1;
        $offset = $limit*($page-1);

        $count = $tidingMdl->count();

        $tidingMdl = $tidingMdl->limit($limit)->offset($offset)->orderBy('Id', 'DESC')->get();

        $taskArr = [];
        $fasinArr = [];

        foreach ($tidingMdl as $t){
            if($t->object_type==1){
                $taskArr[] = $t->object_id;
            }
            if($t->object_type==5){
                $fasinArr[] = $t->object_id;
            }
        }

        $taskMdl = DB::table('tasks')->whereIn('Id',$taskArr)->get();

        $taskIds = [];
        if ($taskMdl->isNotEmpty()){
            $taskIds = array_column($taskMdl->toArray(), 'Id');
        }
//        $fasinMessageMdl = DB::table('amazon_fasin_message')->whereIn('id',$fasinArr)->get();

        foreach ($tidingMdl as $item){
            $item->disabled = 0;
//            // 判断任务是否被删除
            if ($item->object_type == 1){
                foreach ($taskMdl as $t){
                    if ($item->object_id == $t->Id && $t->is_deleted == 1){
                        $item->disabled = 1;
                        break;
                    }
                    if (!in_array($item->object_id, $taskIds)){
                        $item->disabled = 1;
                        break;
                    }
                }
            }
//            if ($item->object_type == 5){
//                $item->disabled = 1;
//                foreach ($fasinMessageMdl as $f){
//                    if ($item->object_id == $f->id){
//                        $item->object_id = $f->fasin;
//                        $item->disabled = 0;
//                        break;
//                    }
//                }
//            }
        }


//		var_dump($return);exit;
//		if(is_array($tidingMdl)){
//			$this->back('获取成功', '200', $tidingMdl);
//		}else{
//			$this->back('获取失败');
//		}
        return $this->back('获取成功', '200', ['count' => $count, 'list' => $tidingMdl]);
	}
	
	/**
	 * 编辑消息
	 * @param Id 用户id
	 */
	public function tiding_update(Request $request){
		$this->validate($request, [
			'Id' => 'required| integer',
		], [
			'Id.required' => 'Id为空',
			'Id.integer' => 'Id必须是整型数字',
		]);
		
		$data = $request->all();
		$call_user = new \App\Libs\wrapper\User();
		$return = $call_user->tiding_update($data);
//		var_dump($return);exit;
		if($return === 1){
			$this->back('操作成功', '200');
		}else{
			$this->back($return);
		}
	}
	
	/**
	 * 修改密码
	 * @param password_log 旧密码
	 * @param password_new 新密码
	 */
	public function password_update(Request $request){
		$this->validate($request, [
			'password_log' => 'required| string',
			'password_new' => 'required| string',
		], [
			'password_log.required' => 'password_log为空',
			'password_log.string' => 'password_log必须是字符串',
			'password_new.required' => 'password_new为空',
			'password_new.string' => 'password_new必须是字符串',
		]);
		$data = $request->all();
		$call_user = new \App\Libs\wrapper\User();
		$return = $call_user->password_update($data);
//		var_dump($return);exit;
		if($return === 1) {
			$this->back('操作成功', '200');
		}else{
			$this->back($return);
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	





}//类结束
